package com.ruoyi.produce.process.bulletin.service;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constant.ERPConstant;
import com.ruoyi.machine.advanced.status.domain.Status;
import com.ruoyi.machine.advanced.status.service.IStatusService;
import com.ruoyi.machine.base.device.domain.Device;
import com.ruoyi.machine.base.device.mapper.DeviceMapper;
import com.ruoyi.produce.base.shift.service.IProduceShiftInfoService;
import com.ruoyi.produce.process.bulletin.domain.Achievement;
import com.ruoyi.produce.process.bulletin.domain.AchievementInfo;
import com.ruoyi.produce.process.bulletin.domain.Mold;
import com.ruoyi.produce.process.bulletin.domain.Packing;
import com.ruoyi.produce.process.bulletin.mapper.BulletinMapper;
import com.ruoyi.produce.process.receiving.domain.ReceivingReportDomain;
import com.ruoyi.produce.process.receiving.domain.ReceivingReportDto;
import com.ruoyi.produce.process.receiving.service.IReceivingReportService;
import com.ruoyi.produce.process.scheduling.domain.Scheduling;
import com.ruoyi.produce.process.scheduling.mapper.SchedulingMapper;
import com.ruoyi.produce.process.worksheet.domain.ProduceWorkSheet;
import com.ruoyi.produce.process.worksheet.service.IProduceWorkSheetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Drj 2021/12/18
 */
@Service
public class  BulletinServiceImpl implements IBulletinService {
    @Autowired
    private BulletinMapper bulletinMapper;
    @Autowired
    private IProduceShiftInfoService produceShiftInfoService;
    @Autowired
    private SchedulingMapper schedulingMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IProduceWorkSheetService workSheetService;
    @Autowired
    private IReceivingReportService ReportService;
    @Autowired
    private IStatusService StatusService;

    @Override
    public List<Mold> selectMoldListNew() {
        // 查询能读到数据的模块
        List<Mold> moldList = bulletinMapper.selectMoldListNew();
        moldList.removeIf(item -> item.geteShiftInfoId() == null && item.getmShiftInfoId() == null);
        for(Mold m :moldList){
            List<ReceivingReportDto> reportList = ReportService.selectReceivingReportBySheetId(m.geteWorkSheetId());
            Double reportUnqualifiedNumber = 0.0;
//            ReceivingReportDto report= ReportService.selectReceivingReportBySheetId(m.geteWorkSheetId());
            Status status=StatusService.selectStatusById(m.getMachineId());
            m.setCompletedRate((double)Math.round((m.getmProduceNumber()/m.getmWorkSheetNumber())*100));
            if (StringUtils.isNotNull(reportList)) {                    // 是否有该验收记录
                for (ReceivingReportDto report : reportList){
                    reportUnqualifiedNumber =+ report.getUnqualifiedNumber();
                }
                m.setDefectiveRate((double)Math.round((reportUnqualifiedNumber/m.getmProduceNumber())*100));
            }else{
                m.setDefectiveRate(0.0);
            }
//            m.setDefectiveRate((double)Math.round((report.getUnqualifiedNumber()/m.getmProduceNumber())*100));
            m.setWorkStatus(status.getWorkStatus());
//            m.setUtzRate((double)Math.round((double)utzQuantity/17*100));
        }
        // 返回之前去看看有没有普通设备的排产记录
        String shiftInfoId = produceShiftInfoService.createShiftInfoId(); //当前班次
        List<Device> deviceList = deviceMapper.selectAllMachineByType(ERPConstant.NORMAL_MACHINE); // 所有普通设备
        for (Device item : deviceList) {
            // 通过班次和设备查询排产记录
            String previousShiftInfoId = createPreviousShiftInfoId(shiftInfoId); //前一个班次
            List<Scheduling> schedulingList = schedulingMapper.selectSchedulingById(previousShiftInfoId, item.getMachineId());
            List<Scheduling> schedulingList1 = schedulingMapper.selectSchedulingById(shiftInfoId, item.getMachineId());
            schedulingList.addAll(schedulingList1);
            for (Scheduling s : schedulingList) {
                Mold mold = new Mold();
                ProduceWorkSheet workSheet = workSheetService.selectProduceWorkSheetById(s.getWorkSheetId());
                List<ReceivingReportDto> reportList = ReportService.selectReceivingReportBySheetId(s.getWorkSheetId());
                Double reportUnqualifiedNumber = 0.0;
                Double reportNumber = 0.0;
//                ReceivingReportDto report= ReportService.selectReceivingReportBySheetId(s.getWorkSheetId());
                if (StringUtils.isNotNull(reportList)) { // 是否有该验收记录
                    for (ReceivingReportDto report : reportList){
                        reportUnqualifiedNumber =+ report.getUnqualifiedNumber();
                        reportNumber = report.getReceivingReportNumber();
                    }
                    mold.setDefectiveRate((double) Math.round((reportUnqualifiedNumber/reportNumber)*100));
                }else{
                    mold.setDefectiveRate(0.0);
                }
                mold.setMachineId(s.getMachineId());
                mold.setMachineName(s.getMachineName());
                mold.setmShiftInfoId(s.getShiftInfoId());
                mold.setmShiftInfoName(s.getShiftInfoName());
                mold.setmWorkSheetId(s.getWorkSheetId());
                mold.setWorkStatus("1");
                mold.setmProduceName(workSheet.getProduceName());
                mold.setmPredictedFinishingTime(workSheet.getPredictedFinishingTime());
                mold.setmWorkSheetNumber(workSheet.getWorkSheetNumber());
                mold.setmProduceNumber(workSheet.getCompletedNumber());
                mold.setmStaffName(workSheet.getCreateByName());
                mold.setCompletedRate((double) Math.round((workSheet.getCompletedNumber()/workSheet.getWorkSheetNumber())*100));
//                if(report.getUnqualifiedNumber()!=0){
//                          mold.setDefectiveRate((double) Math.round((report.getUnqualifiedNumber()/report.getReceivingReportNumber())*100));
//                }else{
//                    mold.setDefectiveRate(0.0);
//                }
                moldList.add(mold);
            }
        }
        return moldList;
    }

    /**
     * 注塑车间看板
     *
     * @return
     */
    @Override
    public List<Mold> selectMoldList() {
        return bulletinMapper.selectMoldList();
    }

    /**
     * 查看包装车间看板
     * @return
     */
    @Override
    public List<Packing> selectPackingList() {
        List<Packing> packingList = new ArrayList<>(); // 返回数组
        String dayShiftId = produceShiftInfoService.createDayShiftId(); //白班编号
        String nightShiftId = produceShiftInfoService.createNightShiftId(); //晚班编号
//        System.out.println("过滤前的加工单" + schedulingMapper.selectSchedulingByShiftInfoId(dayShiftId));
        List<Scheduling> daySchedulingList = filterPackingWorkSheet(schedulingMapper.selectSchedulingByShiftInfoId(dayShiftId)); //白班包装车间的排产记录
//        System.out.println("过滤之后的白班加工单" + daySchedulingList);
        List<Scheduling> nightSchedulingList = filterPackingWorkSheet(schedulingMapper.selectSchedulingByShiftInfoId(nightShiftId)); //晚班包装车间的排产记录
        List<Packing> dayPackingList = createPackingBySchedulingList(daySchedulingList, dayShiftId); //白班包装车间的排产记录生成的包装车间看板
        List<Packing> nightPackingList = createPackingBySchedulingList(nightSchedulingList, nightShiftId); //晚班包装车间的排产记录生成的包装车间看板
        packingList.addAll(dayPackingList);
        packingList.addAll(nightPackingList);
        return packingList;
    }

    /**
     * 注塑车间柱状图
     *
     * @return
     */
    @Override
    public List<Achievement> selectAchievementInfoListForMold() {
        List<Achievement> achievements = bulletinMapper.selectAchievementInfoListForMold();
        for (Achievement a : achievements) {
            a.setAchievementInfoList(bulletinMapper.selectAchievementInfoList(new AchievementInfo(a)));
        }
        return achievements;
    }

    /**
     * 包装车间柱状图
     *
     * @return
     */
    @Override
    public List<Achievement> selectAchievementInfoListForPack() {
        List<Achievement> achievements = bulletinMapper.selectAchievementInfoListForPack();
        for (Achievement a : achievements) {
            a.setAchievementInfoList(bulletinMapper.selectAchievementInfoList(new AchievementInfo(a)));
        }
        return achievements;
    }

    /**
     * 过滤掉没有设备的加工单（包装车间的）
     * @param schedulingList
     * @return
     */
    public List<Scheduling> filterPackingWorkSheet(List<Scheduling> schedulingList) {
        Map<String, Scheduling> map = new HashMap<>();
        for (int i = 0; i < schedulingList.size(); i++) {
            map.put(schedulingList.get(i).getWorkSheetId(), schedulingList.get(i));
        }
        for (int i = 0; i < schedulingList.size(); i++) {
            // 排产，过滤掉有设备的加工单
            if (!schedulingList.get(i).getMachineId().equals("")) {
                // 有设备
                map.remove(schedulingList.get(i).getWorkSheetId());
            }
        }
        return new ArrayList<>(map.values());
    }

    /**
     * 创建包装对象，通过设备排产列表
     * @param schedulingList
     * @return
     */
    public List<Packing> createPackingBySchedulingList(List<Scheduling> schedulingList, String shiftInfoId) {
        List<Packing> packingList = new ArrayList<>();
        for (Scheduling item : schedulingList) {
            Packing packing = new Packing();
            packing.setShiftInfoId(shiftInfoId);
            packing.setWorkSheetId(item.getWorkSheetId());
            ProduceWorkSheet workSheet = workSheetService.selectProduceWorkSheetById(item.getWorkSheetId());
            packing.setProduceName(workSheet.getProduceName());
            packing.setWorkSheetNumber(workSheet.getWorkSheetNumber());
            packing.setProduceNumber(workSheet.getCompletedNumber());
            packing.setStaffName(workSheet.getCreateByName());
            packingList.add(packing);
        }
        return packingList;
    }

    /**
     * 生成当前班次的前一个班次
     *
     * @return
     */
    String createPreviousShiftInfoId(String shiftInfoId) {
        String id = shiftInfoId.substring(shiftInfoId.length() - 2);
        String res = "";
        switch (id) {
            case "01":
                // 白班，生成前一天晚班
                res = produceShiftInfoService.createYesterdayNightShiftId();
                break;
            case "02":
                Date date = new Date();
                Calendar currentCalendar = new GregorianCalendar();
                currentCalendar.setTime(date);
                int currentHour = currentCalendar.get(Calendar.HOUR_OF_DAY);// 获取小时
                // 当天晚班，生成当天白班
                if (currentHour >= 19) {
                    res = produceShiftInfoService.createDayShiftId();
                }
                // 第二天凌晨的晚班，生成前一天的白班
                else if (currentHour < 7) {
                    res = produceShiftInfoService.createYesterdayDayShiftId();
                }

                break;
        }
        return res;
    }
}
